package com.lahuan.rpc.loadbalance;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * @author lfy
 */
public class CustomLoadBalance implements LoadBalance {
    public CustomLoadBalance(){
        System.out.println("CustomLoadBalance init()");
    }
    RandomLoadBalance randomLoadBalance = new RandomLoadBalance();
    String time = null;
    int count = 0;
    int maxCount = 10;
    @Override
    public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
        System.out.println("CustomLoadBalance");
        //限流规则和拒绝
        check();
        //如果通过限流规则，这里就直接使用dubbo自带的随机负载均衡,就不自定义了
        return randomLoadBalance.select(invokers,url,invocation);
    }
    private void check() {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        Calendar calendar = Calendar.getInstance();
        String curTime = df.format(calendar.getTime());
        //看看是不是和之前一样的分钟
        if(curTime.equals(time)){
            if(++count >=maxCount){
                throw new RuntimeException("超过限流阈值.");
            }
        }else{
            time = curTime;
            count = 1;
        }
    }
}
